import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UIFrameLoad')
export class UIFrameLoad extends Component {
    @property(Prefab)
    jay : Prefab = null;

    @property(Node)
    content : Node = null;

    timeEveryFrame : number = 0.016;     //单位毫秒
    itemCount : number = 0;
    event : any = null;

    onEnable(){
        
    }
    onDisable(){
        this.btnCallback(null,'clear')
    }

    /**
     * 分帧加载
     * @param itemCount 加载的项目的数量
     * @param event 要对项目做的操作 比如说 初始化Item
     * @param percent 占用每一帧多少比例的时间
     * @param node 一个节点用来调用定时器,这个很随意
     * @example
        let fuben = GameConfig[kind].concat();
        let callback = (i)=>{
            let item = this.getIconNode();
            item.parent = this.GridContent;
            item.getComponent('IconPrefab').setPropInfo(fuben[i], this);
        }
        FrameLoad.initScrollView(fuben.length,callback,0.5,this.node);
     * 
     */
    async initScrollView (itemCount,event,percent,node) {
        this.itemCount = itemCount;
        this.event = event;
        await this.executePreFrame(this.gener(),percent,node);
    }

    *gener(){
        for(let i=0;i<this.itemCount;i++){
            yield this.event && this.event(i);
        }
    }

    executePreFrame(generator: Generator, percent: number,node) {
        var duration = this.timeEveryFrame * percent;
        return new Promise<void>((resolve, reject) => {
            let gen = generator;
            let execute = () => {
                let startTime = new Date().getTime();

                for (let iter = gen.next(); ; iter = gen.next()) {
                    if (iter == null || iter.done) {
                        resolve();
                        return;
                    }
                    if (new Date().getTime() - startTime > duration) {
                        node.getComponent(Component).scheduleOnce(() => {
                            execute();
                        });
                        return;
                    }
                }
            };
            // 运行执行函数
            execute();
        });
    }

    btnCallback(event,data){
        if (data == 'clear'){
            this.content.removeAllChildren();
        }
        else if (data == '直接加载'){
            for(let i = 0; i< 5000;i++){
                let node = instantiate(this.jay);
                node.parent = this.content;
            }
        }
        else if (data == '分帧加载'){
            let func = ()=>{
                let node = instantiate(this.jay);
                node.parent = this.content;
            }
            this.initScrollView(5000,func,0.5,this.node);
        }
    }
}

